<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use frontend\models\SysItem;
use yii\filters\AccessControl;
use yii\data\Pagination;
use backend\models\GrpClass;
use backend\models\GrpBrand;
use backend\models\GrpColor;
use backend\models\GrpStyle;
use frontend\models\SysSession;
use frontend\models\ItemPriceTable;
use frontend\models\UserShoppingCart;
use yii\db\ActiveRecord;
use frontend\models\UserFavourite;
use frontend\models\User;
use backend\models\SysUserDesigner;
use yii\helpers\Url;
use backend\models\SysItemSearch;
use frontend\models\LogUserFootprint;
use frontend\models\UserInfo;
use backend\models\PrfConfig;
use backend\models\LogUserScore;
use frontend\models\UserModelDownload;

class ItemController extends Controller
{
    public function actionVideo()
    {
        return $this->render('video');
    }

    public function actionIndex2()
    {
        $searchModel = new SysItemSearch();
        $dataProvider = $searchModel->searchFront(Yii::$app->request->queryParams);
        $color_arr = GrpColor::find()->asArray()->all();
        $style_arr = GrpStyle::find()->asArray()->all();
        $brand_arr = GrpBrand::allBrand();
        return $this->render('index2', [
            'queryParams' => Yii::$app->request->queryParams,
            'dataProvider' => $dataProvider,
            'color_arr' => $color_arr,
            'style_arr' => $style_arr,
            'brand_arr' => $brand_arr,
        ]);
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['add-shop-car'],
                'rules' => [
                    [
                        'actions' => ['add-shop-car'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    private function getAllBrand()
    {
        $brand_array = GrpBrand::findBySql("SELECT grp_brand.id,grp_brand.`name`,grp_brand.`order`,grp_brand_head.`name` AS brand_class,grp_brand_head.`order` AS brand_class_order
            FROM grp_brand LEFT JOIN grp_brand_head ON grp_brand.head_grp=grp_brand_head.id WHERE grp_brand.useing=1 
            ORDER BY grp_brand_head.`order` DESC,grp_brand.`order` ASC;")->asArray()->all();
        $brand_array2 = array();
        for ($i = 0, $j = 0; $i < count($brand_array); $i++) {
            if ($i == 0 || $i > 0 && $brand_array[$i]["brand_class_order"] != $brand_array[$i - 1]["brand_class_order"]) {
                $j = 0;
            }
            $brand_array2[$brand_array[$i]["brand_class"]][$j++] = [
                'id' => $brand_array[$i]['id'],
                'name' => $brand_array[$i]['name']
            ];
        }
        return $brand_array2;
    }

    private function getAllColor()
    {
        return $color_array = GrpColor::find()->asArray()->all();
    }

    private function getAllStyle()
    {
        return $style_array = GrpStyle::find()->asArray()->all();
    }

    public function actionIndex()
    {
        $conditions = "";
        $tables = "";
        $fields = "";

        if (Yii::$app->request->get('order') == 'model') {
            //获取所有已经上传的model id
            $filePath = Yii::$app->params['3dPath'];
            //$filePath='D:/model';
            //PHP遍历文件夹下所有文件
            $handle = opendir($filePath . '/');
            //定义用于存储文件名的数组
            $itemIds = array();
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && substr(strrchr($file, '.'), 1) == 'zip') {
                    $itemIds[] = basename($file, ".zip"); //输出文件名
                }
            }
            closedir($handle);
            //获取结束

            $conditions .= " AND sys_item.id IN (" . implode(',', $itemIds) . ")";
        }

        if ($brand_id = intval(Yii::$app->request->get('brand'))) {
            $fields .= ",grp_brand.`name` AS brand_name ";
            $conditions .= " AND sys_item.brand_id=" . addslashes(Yii::$app->request->get('brand'));
        }
        if ($search = Yii::$app->request->get('q')) {
            $search = addslashes($search);
            $getId2 = GrpBrand::findOne(['name' => $search]);
            if (!empty($getId2)) {
                $getId = $getId2->id;
            } else {
                $getId = "";
            }
            $conditions .= " AND (sys_item.name like '%" . addslashes($search) . "%' 
                                OR sys_item.gjj_code like '%" . addslashes($search) . "%'
                                OR sys_item.factory_code like '%" . addslashes($search) . "%'
                                OR sys_item.brand_id = '" . $getId . "'
                                ) ";
        }
        $class1_array = GrpClass::findBySql("SELECT * FROM grp_class WHERE father=0 AND id<>800000000 ORDER BY t_order DESC")->asArray()->all();
        if ($class_id = intval(Yii::$app->request->get('class'))) {
            $fields .= ",grp_class.`name` AS class_name ";
            $tables .= ",grp_class ";
            if ($class_id % 100000000 == 0) {
                $class1 = $class_id;
                $class_type = 1;
                $class2_array = GrpClass::find()->where(['father' => $class1])->asArray()->all();
                $conditions .= " AND sys_item.class_id=grp_class.id AND sys_item.class_id like '" . intval($class_id / 100000000) . "%'";
            } elseif ($class_id % 1000000 == 0) {
                $class1 = intval($class_id / 100000000) * 100000000;
                $class2 = $class_id;
                $class_type = 2;
                $class2_array = GrpClass::find()->where(['father' => $class1])->asArray()->all();
                $class3_array = GrpClass::find()->where(['father' => $class2])->asArray()->all();
                $conditions .= " AND sys_item.class_id=grp_class.id AND sys_item.class_id like '" . intval($class_id / 1000000) . "%'";
            } elseif ($class_id % 10000 == 0) {
                $class1 = intval($class_id / 100000000) * 100000000;
                $class2 = intval($class_id / 1000000) * 1000000;
                $class3 = $class_id;
                $class_type = 3;
                $class2_array = GrpClass::find()->where(['father' => $class1])->asArray()->all();
                $class3_array = GrpClass::find()->where(['father' => $class2])->asArray()->all();
                $conditions .= " AND sys_item.class_id=grp_class.id AND sys_item.class_id=" . addslashes(Yii::$app->request->get('class'));
            }
        }
        if ($color_id = intval(Yii::$app->request->get('color'))) {
            $fields .= ",grp_color.`name` AS color_name ";
            $tables .= ",grp_color,sys_item_color ";
            $conditions .= " AND grp_color.id=sys_item_color.color_id AND sys_item.id=sys_item_color.item_id AND sys_item_color.color_id=" . addslashes(Yii::$app->request->get('color'));
        }
        if ($style_id = intval(Yii::$app->request->get('style'))) {
            $fields .= ",grp_style.`name` AS style_name ";
            $tables .= ",grp_style,sys_item_style ";
            $conditions .= " AND grp_style.id=sys_item_style.style_id AND sys_item.id=sys_item_style.item_id AND sys_item_style.style_id=" . addslashes(Yii::$app->request->get('style'));
        }
        Yii::$app->request->get('range');
        Yii::$app->request->get('order');
        Yii::$app->request->get('pageSize') && intval(Yii::$app->request->get('pageSize')) <= 52 && intval(Yii::$app->request->get('pageSize')) >= 20 ? $pageSize = intval(Yii::$app->request->get('pageSize')) : $pageSize = 28;

        $query0 = "SELECT DISTINCT sys_item.id 
                FROM sys_item,sys_image large_img,sys_image middle_img,sys_image small_img" . $tables . " 
                WHERE sys_item.app_return=1 AND sys_item.img_url_id=large_img.id AND sys_item.img_thumb_id=middle_img.id AND sys_item.img_small_id=small_img.id" . $conditions;
        $count = SysItem::findBySql($query0)->count();

        $pagination = new Pagination([
            "defaultPageSize" => $pageSize,
            "totalCount" => $count
        ]);

        $get_order = yii::$app->request->get('order');
        $allOrder = [
            'priceasc' => 'sys_item.price_base ASC',
            'pricedesc' => 'sys_item.price_base DESC',
            'datedesc' => 'sys_item.update_at DESC',
            'dateasc' => 'sys_item.update_at ASC',
            'model' => 'sys_item.price_base ASC',
        ];
        if (isset($get_order)) {
            $orderStatus = $allOrder[$get_order];
        } else {
            $orderStatus = "sys_item.top_time DESC, 
                            sys_item.id DESC";
        }

        $query = "SELECT DISTINCT sys_item.id,
                                sys_item.`name`,
                                sys_item.price_base,
                                large_img.url AS large_img_url, 
                                middle_img.url AS middle_img_url,
                                small_img.url AS small_img_url" . $fields . " 
                FROM sys_item LEFT JOIN grp_brand ON sys_item.brand_id=grp_brand.id ,
                     sys_image large_img,
                     sys_image middle_img,
                     sys_image small_img" . $tables . " 
                WHERE sys_item.app_return=1 
                      AND grp_brand.useing=1 
                      AND sys_item.img_url_id=large_img.id 
                      AND sys_item.img_thumb_id=middle_img.id 
                      AND sys_item.img_small_id=small_img.id" . $conditions . " 
                ORDER BY " . $orderStatus . ", 
                         sys_item.id DESC 
                LIMIT " . $pagination->offset . "," . $pagination->limit;
        $model_item = SysItem::findBySql($query)->asArray()->all();

        return $this->render('index', [
            'model_item' => $model_item,
            'pagination' => $pagination,
            'class1_array' => isset($class1_array) ? $class1_array : null,
            'class1_id' => isset($class1) ? $class1 : null,
            'class2_array' => isset($class2_array) ? $class2_array : null,
            'class2_id' => isset($class2) ? $class2 : null,
            'class3_array' => isset($class3_array) ? $class3_array : null,
            'class3_id' => isset($class3) ? $class3 : null,
            'brand_array' => $this->getAllBrand(),
            'brand_id' => isset($brand_id) ? $brand_id : null,
            'get_brandtype' => Yii::$app->request->get("brandtype"),
            'color_array' => $this->getAllColor(),
            'color_id' => isset($color_id) ? $color_id : null,
            'style_array' => $this->getAllStyle(),
            'style_id' => isset($style_id) ? $style_id : null,
            'pageSize' => isset($pageSize) ? $pageSize : null,
            'get_order' => isset($get_order) ? $get_order : null,
        ]);
    }

    public function actionAddShopCar()
    {
        if (Yii::$app->request->isAjax && Yii::$app->request->isPost) {
            $order_arr = json_decode(Yii::$app->request->post('str'), true);
            if (intval($order_arr['type']) == 0 && $order_arr['count'] >= 1 && $order_arr['item_id'] > 1) {
                $data = [
                    "info" => [],
                    "items" => []
                ];
                $data['info']['count'] = 1;
                $data['info']['cart_type'] = 0;
                $data['items'][0] = [
                    "item_id" => $order_arr['item_id'],
                    "price_id" => $order_arr['price_id'],
                    "count" => $order_arr['count'],
                    "sku_id" => $order_arr['sku_id']
                ];
            } else {
                echo 0;
                return;
            }
            $shopping = new UserShoppingCart();
            $shopping->user_id = Yii::$app->user->identity->id;
            $shopping->type = intval($order_arr['type']);
            $shopping->jsondata = json_encode($data);
            $shopping->count = intval($order_arr['count']);
            $shopping->createtime = strtotime('now');
            echo $shopping->save() ? 1 : 0;
            Yii::$app->session['userShoppingCartCount'] = UserShoppingCart::find()->where(['user_id' => Yii::$app->user->identity->id])->count();
        }
    }

    public function actionItemInfo()
    {
        isset($_GET['item_id']) ? $item_id = intval(Yii::$app->request->get('item_id')) : '';
        $this->filePath = Yii::$app->params['3dPath'];
        //$this->filePath='D:\model';
        if (file_exists($this->filePath . '/' . $item_id . ".zip")) {
            $hasmodel = true;
        } else {
            $hasmodel = false;
        }
        $hasAddFavourite = false;
        $id = get_magic_quotes_gpc() ? intval(Yii::$app->request->get('item_id')) : intval(addslashes(Yii::$app->request->get('item_id')));
        if (!Yii::$app->user->isGuest) {
            //记录足迹
            $userFoot = new LogUserFootprint();
            $userFoot->uid = Yii::$app->user->identity->id;
            $userFoot->calltime = time();
            $userFoot->action = 'item';
            $userFoot->action_id = $id;
            $userFoot->title = $userFoot->item0->name;
            $userFoot->save();
            //记录足迹结束
            $user_id = Yii::$app->user->identity->id;
            $user = SysSession::find()->where(['uid' => $user_id])->asArray()->all();
            if ($user) {
                $user_info = [
                    'id' => $user_id,
                    'session' => $user[0]['session'],
                    'token' => $user[0]['token']
                ];
            }
            $res = UserFavourite::findOne(['uid' => $user_id, 'type' => 1, 'type_id' => $id]);
            if (!empty($res)) {
                $hasAddFavourite = true;
            }
        }
        if (Yii::$app->request->isGet && $id > 1) {
            //获取更多信息
            $sql = "SELECT 
                sys_item.`name` AS item_name,
                sys_item.gjj_code,
                sys_item.factory_code,
                grp_brand.`name` AS brand_name,
                grp_sery.`name` AS sery_name,
                grp_style.`name` AS style_name,
                grp_space.`name` AS space_name,
                grp_place.`name` AS place_name,
                sys_item.top_surface,
                sys_item.structure,
                sys_item.filling,
                sys_item.metals,
                sys_item.supply_cycle,
                preview.coating,
                sys_item_size.size,
                sys_item_size.volume,
                base_sys_material.`name` AS material_name
            FROM `sys_item`
            LEFT JOIN grp_brand ON sys_item.brand_id=grp_brand.id
            LEFT JOIN sys_item_sery ON sys_item.id=sys_item_sery.item_id
            LEFT JOIN grp_sery ON sys_item_sery.sery_id=grp_sery.id
            LEFT JOIN sys_item_style ON sys_item_style.item_id=sys_item.id
            LEFT JOIN grp_style ON sys_item_style.style_id=grp_style.id
            LEFT JOIN sys_item_space ON sys_item_space.item_id=sys_item.id
            LEFT JOIN grp_space ON grp_space.id=sys_item_space.space_id
            LEFT JOIN sys_item_place ON sys_item_place.item_id=sys_item.id
            LEFT JOIN grp_place ON sys_item_place.place_id=grp_place.id
            LEFT JOIN sys_item_size ON sys_item_size.item_id=sys_item.id 
            LEFT JOIN base_sys_material ON sys_item.material_list=base_sys_material.id
            LEFT JOIN (SELECT item_id,group_concat(coating) AS coating FROM base_sys_preview WHERE item_id = " . $id . " GROUP BY item_id) preview ON preview.item_id=sys_item.id
            WHERE sys_item.app_return=1 AND sys_item.id=" . $id;
            $moreInfo1 = ActiveRecord::findBySql($sql)->asArray()->all();
            //一对多的信息 （色系、风格）
            //颜色
            $sql = "SELECT 
                GROUP_CONCAT(grp_color.`name`) AS color_name
            FROM grp_color 
            WHERE grp_color.id
            IN ( 
                SELECT sys_item_color.color_id 
                FROM sys_item 
                LEFT JOIN `sys_item_color` ON sys_item.id=sys_item_color.item_id 
                WHERE sys_item.id=" . $id .
                ")";
            $moreInfo2 = ActiveRecord::findBySql($sql)->asArray()->all();
            //风格
            $sql = "SELECT 
                GROUP_CONCAT(grp_sery.`name`) AS sery_name
            FROM grp_sery 
            WHERE grp_sery.id
            IN ( 
                SELECT sys_item_sery.sery_id 
                FROM sys_item 
                LEFT JOIN `sys_item_sery` ON sys_item.id=sys_item_sery.item_id 
                WHERE sys_item.id=" . $id .
                ")";
            $moreInfo3 = ActiveRecord::findBySql($sql)->asArray()->all();
            //单元格内有多个数据（面料）
            $sql = "SELECT
                sys_item.fabric_list 
            FROM `sys_item`
            WHERE sys_item.id = " . $id;
            $moreInfo4 = ActiveRecord::findBySql($sql)->asArray()->all();
            if (empty($moreInfo1) || empty($moreInfo2) && empty($moreInfo3) && empty($moreInfo4)) {
                $this->redirect(['item/index']);
            }
            if (!empty($moreInfo4[0]["fabric_list"])) {
                $sql = "SELECT 
                    GROUP_CONCAT(base_sys_fabric.`name`) AS fabric_name
                FROM base_sys_fabric
                WHERE base_sys_fabric.id 
                IN ( 
                    " . $moreInfo4[0]["fabric_list"] . "
                )";
                $moreInfo5 = ActiveRecord::findBySql($sql)->asArray()->all();
                $moreInfo1[0] = $moreInfo1[0] + $moreInfo2[0] + $moreInfo3[0] + $moreInfo5[0];
            } else {
                $moreInfo1[0] = $moreInfo1[0] + $moreInfo2[0] + $moreInfo3[0];
            }
            //信息合并
            $moreInfo = $moreInfo1;
            //获取基本信息
            $sql = "SELECT sys_item.id,
                         sys_item.`name` AS item_name,
                         sys_item.price_base,
                         sys_item.price_discount,
                         sys_item.tips,
                         small_img.url AS small_img_url ,
                         middle_img.url AS middle_img_url,
                         large_img.url AS large_img_url,
                         grp_brand.`name` AS brand_name,
                         sys_item.class_id 
                  FROM `sys_item`,
                        sys_image small_img,
                        sys_image middle_img,
                        sys_image large_img,
                        grp_brand
                  WHERE sys_item.id=" . $id . " AND sys_item.img_url_id=large_img.id AND sys_item.img_thumb_id=middle_img.id AND sys_item.img_small_id=small_img.id AND grp_brand.id=sys_item.brand_id";
            $item = SysItem::findBySql($sql)->asArray()->all();

            //获取class信息
            $class_id = intval($item[0]['class_id']);
            if ($class_id % 100000000 == 0) {
                $class1 = $class_id;
                $result = GrpClass::find()->where(['id' => $class_id])->asArray()->all();
                $class_array = [
                    '1' => [
                        'id' => $class1,
                        'name' => $result[0]['name']
                    ]
                ];
            } elseif ($class_id % 1000000 == 0) {
                $class1 = intval($class_id / 100000000) * 100000000;
                $class2 = $class_id;
                $result = GrpClass::findBySql('SELECT class1.`name` AS name1,class2.`name` AS name2 
                    FROM grp_class class1,grp_class class2 
                    WHERE class1.id=class2.father AND class2.id=' . $class2)->asArray()->all();
                $class_array = [
                    '1' => [
                        'id' => $class1,
                        'name' => $result[0]['name1']
                    ],
                    '2' => [
                        'id' => $class2,
                        'name' => $result[0]['name2']
                    ],
                ];
            } elseif ($class_id % 10000 == 0) {
                $class1 = intval($class_id / 100000000) * 100000000;
                $class2 = intval($class_id / 1000000) * 1000000;
                $class3 = $class_id;
                $result = GrpClass::findBySql('SELECT class1.`name` AS name1,class2.`name` AS name2,class3.`name` AS name3
                    FROM grp_class class1,grp_class class2,grp_class class3
                    WHERE class1.id=class2.father AND class2.id=class3.father AND class3.id=' . $class3)->asArray()->all();
                $class_array = [
                    '1' => [
                        'id' => $class1,
                        'name' => $result[0]['name1']
                    ],
                    '2' => [
                        'id' => $class2,
                        'name' => $result[0]['name2']
                    ],
                    '3' => [
                        'id' => $class3,
                        'name' => $result[0]['name3']
                    ]
                ];
            }
            $sql = "";

            $sql = "SELECT DISTINCT small_img.url AS small_img_url ,middle_img.url AS middle_img_url,large_img.url AS large_img_url
                FROM sys_image small_img,sys_image middle_img,sys_image large_img,base_sys_preview LEFT JOIN base_sys_preview_angle ON base_sys_preview.id=base_sys_preview_angle.pid
                WHERE base_sys_preview.item_id=" . $id . " AND base_sys_preview_angle.img_small_id=small_img.id AND base_sys_preview_angle.img_thumb_id=middle_img.id AND base_sys_preview_angle.img_url_id=large_img.id";
            $angles = SysItem::findBySql($sql)->asArray()->all();

            $itemObj = new SysItem();
            $sellersLocation = $itemObj->findOne(['id' => $id])->sellersLocation;

            $itemPriceTable = new ItemPriceTable($id);
            $fields = json_encode($itemPriceTable->fields);
            $price = json_encode($itemPriceTable->getPriceTable());
            $previewTable = json_encode($itemPriceTable->previewTable);
            return $this->render('itemInfo', [
                'hasAddFavourite' => $hasAddFavourite,
                'item_info' => $item[0],
                'angles' => $angles,
                'class_array' => $class_array,
                'user_info' => isset($user_info) ? $user_info : null,
                'fields' => $fields,
                'price' => $price,
                'previewTable' => $previewTable,
                'moreInfo' => $moreInfo[0],
                'sellersLocation' => $sellersLocation,
                'hasmodel' => $hasmodel
            ]);
        } else {
            $this->redirect(['item/index']);
        }
    }

    public function actionDownload()
    {
        if (isset($_GET['q']) && $_GET['q'] == 'model') {
            return $this->downloadModelVerify();
        } else {
            return $this->render('error', [
                'name' => '错误',
                'message' => '您的请求有误。',
                'redirectUrl' => Url::to(['item/index']),
            ]);
        }
    }

    private function downloadModelVerify()
    {
        isset($_GET['item_id']) ? $item_id = intval(Yii::$app->request->get('item_id')) : '';
        $this->filePath = Yii::$app->params['3dPath'];
        //$this->filePath='D:\model';
        $zoroTime = strtotime(date('Y-m-d', time()));
        if (isset(Yii::$app->user->identity->id)) {
            $uid = Yii::$app->user->identity->id;
            $userInfo = UserInfo::findOne(['id' => $uid]);
            //下载完一个模型三天内改模型下载不扣积分
            $threeday = time() - 24 * 60 * 60 * 3;
            $isDowned = UserModelDownload::find()->where("uid = {$uid} AND item_id = {$item_id} AND duplicate_download = 0 AND download_time > {$threeday}")->exists();
            if ($isDowned) {
                $this->downloadModel($item_id);
                $this->logDownload($uid, $item_id, true);
                return;
            }
            $allScore = LogUserScore::find()->where(['uid' => $uid])->sum('score');
            $countDown = UserModelDownload::find()->select(['item_id'])->distinct()->where(['and', ['uid' => $uid, 'duplicate_download' => 0], ['>', 'download_time', $zoroTime]])->count();
            //注册用户和内部员工 (1,2,8)
            if (in_array($userInfo->user_type, [1, 2, 8])) {
                $limit = PrfConfig::findOne(['config_attribute' => 'register_model_download']);
            } //VIP会员用户模型下载消耗积分[3,1]
            elseif ($userInfo->user_type == 3 && $userInfo->user_type_class == 1) {
                $limit = PrfConfig::findOne(['config_attribute' => 'designer_model_download']);
            } //付费VIP会员用户模型下载消耗积分[3,5]
            elseif ($userInfo->user_type == 3 && $userInfo->user_type_class == 5) {
                $limit = PrfConfig::findOne(['config_attribute' => 'super_model_download']);
            } //装饰运营商渠道用户模型下载消耗积分(4,5,6,7)
            elseif (in_array($userInfo->user_type, [4, 5, 6, 7])) {
                $limit = PrfConfig::findOne(['config_attribute' => 'company_model_download']);
            }
            //判断今天下载次数 和积分
            if ($allScore >= $limit->config_value && $countDown < $limit->description) {
                $this->downloadModel($item_id);
                $this->logDownload($uid, $item_id);
                $score = $limit->config_value;
                $this->logSocre($uid, $score);
            } else {
                return $this->render('error', [
                    'name' => '',
                    'message' => '您的积分不足或者今天已经超过下载次数。',
                    'redirectUrl' => Url::to(['item/item-info', 'item_id' => $item_id]),
                ]);
            }
        } else {
            return $this->render('error', [
                'name' => '',
                'message' => '您需要注册才能下载模型。',
                'redirectUrl' => Url::to(['site/login'])
            ]);
        }

    }

    private function logDownload($uid, $item_id, $isduplicate = false)
    {
        $logDown = new UserModelDownload();
        $logDown->uid = $uid;
        $logDown->download_time = time();
        $logDown->item_id = $item_id;
        if ($isduplicate) {
            $logDown->duplicate_download = 1;
        }
        $logDown->save();
    }

    private function logSocre($uid, $score)
    {
        if ($score == 0) {
            return;
        }
        $logSocre = new LogUserScore();
        $logSocre->uid = $uid;
        $logSocre->score = $score * -1;
        $logSocre->score_key = 'model_download';
        $logSocre->time = time();
        $logSocre->state = 4;
        $logSocre->memo = '模型下载消费';
        $logSocre->save();
    }

    private function downloadModel($item_id)
    {
        $filename = $item_id . '.zip';
        $virtalPath = '/model_file';
        $filePath = realpath($this->filePath . '/' . $filename);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match('/MSIE/', $ua)) {
            header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
        } elseif (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
        } else {
            header('Content-Disposition: attachment; filename="JAJAHOME 3D模型文件' . $filename . '"');
        }

        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');
        header('Content-Length: ' . filesize($filePath));

        if (strpos($_SERVER["SERVER_SOFTWARE"], 'Apache') !== false) {
            header('X-Sendfile: ' . $filePath);
        } elseif (strpos($_SERVER["SERVER_SOFTWARE"], 'nginx') !== false) {
            header('X-Accel-Redirect: ' . $virtalPath . '/' . $filename);
        } else {
            set_time_limit(300);
            ob_end_clean();
            readfile($filePath);
        }
    }

    private $filePath;
}
